import React, { Component } from 'react';
import axios from 'axios';
import { Tooltip, Input, Icon } from 'antd';

export default class NoteBookMenu extends Component{
    constructor(props){
        super(props);
    }
    render(){
        return (
            <div>
                <BookMenuHead/>
                <div className="underline"></div>
                <BookMenuList/>
            </div>
        );
    }
}

class BookMenuHead extends Component{
    constructor(props){
        super(props);
    }
    add_book = (event) => {
        // 定义覆盖所有布局组件标记
        PubSub.publish('cover_flag', true);
        PubSub.publish('cover_component', 'AddBook');
    }
    search_books = (event) =>{
        axios.get('/api/book', { params: { search_book: event.target.value } })
         .then(function(response){
            if(response.data.code == 200){
                PubSub.publish('books_list', response.data.data);
            }else{
                //todo
            }
         })
         .catch(function(error){
             console.log(error);
         })
    }
    render(){
        return (
            <div>
                <div className="book-menu-title">
                    <span>笔记本</span>
                    <Tooltip placement="bottomLeft" title="新建笔记本">
                            <i className="icon add-img" onClick={ this.add_book }></i>
                    </Tooltip>
                </div>
                <div className="search-book-input">   
                    <Input prefix={<Icon type="search" style={{ color: 'rgba(0,0,0,.25)' }} />} size="default" placeholder="查找笔记本" onChange={ this.search_books } />   
                </div>
            </div>
        );
    }
}


class BookMenuList extends Component{
    constructor(props){
        super(props);
        this.state = { books_list: [] };
    }
    componentDidMount(){
        let that = this;
        axios.get('/api/book')
            .then(function (response) {
                if(response.data.code == 200){
                    that.setState ({ books_list: response.data.data });
                }else{
                    //todo
                }
            })
            .catch(function (error) {
                console.log(error);
        });
        // 模糊查询笔记本标题实时更新笔记本列表
        this.pubsub_token = PubSub.subscribe('books_list', function (topic, message) {  
            this.setState({  
                books_list: message  
            });
        }.bind(this));  
    }
    render(){
        let books_list = this.state.books_list.map((data)=> (
            <div className="book-list" key={ data.book_id }>
                <p className="title">{ data.book_title }</p>
                <p className="count">{ data.bijis_count }条笔记</p>
            </div>
        ));
        return (
            <div className="book-menu-list">
                <div className="book-list-title">最近笔记本</div>
                { books_list }
            </div>
        );
    }
}